package com.mall.struts.action;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.mall.ibatis.bean.Frame;
import com.mall.ibatis.bean.Operator;
import com.mall.ibatis.bean.OperatorStatus;
import com.mall.ibatis.bean.ReturnMessage;
import com.mall.service.FunctionService;
import com.mall.service.OperatorService;
import com.mall.service.OperatorStatusService;
import com.mall.util.JQGridUtil;
import com.mall.util.StringUtil;


public class OperatorAction extends Action
{
	private static Log logger = LogFactory.getLog(OperatorAction.class);
	private static final OperatorService operatorService =  OperatorService.getInstance();
	private static final FunctionService functionService = FunctionService.getInstance();
	private static final OperatorStatusService operatorStatusService = OperatorStatusService.getInstance();
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	{
		String method = request.getParameter("type");
		try
		{
			if(method == null)
			{
				
			}
			else if(method.equals("query"))
			{
				return query(mapping, form, request, response);
			}
			else if(method.equals("login"))
			{
				return login(mapping, form, request, response);
			}
			else if(method.equals("logout"))
			{
				return logout(mapping, form, request, response);
			}
			
			else if(method.equals("modifyPassword"))
			{
				return modifyPassword(mapping, form, request, response);
			}
			
			else if(method.equals("loading"))
			{
				return loading(mapping,form,request,response);
			}
			else if(method.equals("list"))
			{
				return list(mapping,form,request,response);
			}
			else if(method.equals("detail"))
			{
				return detail(mapping, form, request, response);
			}
			else if(method.equals("update"))
			{
				return update(mapping, form, request, response);
			}
			else if(method.equals("insert"))
			{
				return insert(mapping, form, request, response);
			}
			
			else if(method.equals("delete"))
			{
				return delete(mapping, form, request, response);
			}
			else if(method.equals("updatePassword"))
			{
				return updatePassword(mapping, form, request, response);
			
			}else if("addMethod".equals(method)){
				return addMethod(mapping,form,request,response);
			}else if("methodIsCheck".equals(method)){
				return methodIsCheck(mapping,form,request,response);
			}else if("addDataScope".equals(method)){
				return addDataScope(mapping,form,request,response);
			}else if("selectDataScope".equals(method)){
				return selectDataScope(mapping,form,request,response);
			}else if("frame".equals(method)){
				return frame(mapping,form,request,response);
			}
			
			
			else if(method.equals("selectStreetChargers"))
			{
				return selectStreetChargers(mapping,form,request,response);
			}
			
		}
		catch (Exception e)
		{
			// TODO: handle exception
			request.setAttribute("exceptionMsg", e.getMessage());
			logger.error(e);
			return mapping.findForward("exceptionError");
		}
		
		return mapping.findForward("pageNotFoundError");
		
	}
	
	//管理架构功能树一次性加载
	private ActionForward frame(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		List<Frame> frameList = operatorService.frame();
		request.setAttribute("frameList",frameList);
		return mapping.findForward("frameAllTree");
	}

	//通过用户的Id查询出相应的数据范围名称以及Id
	private ActionForward selectDataScope(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,HttpServletResponse response) throws Exception{
		String opId = request.getParameter("opId");
		
		String xmlStr = operatorService.selectDataScope(opId);
		response.setContentType("text/xml;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.print(xmlStr);
		out.flush();
		out.close();
		return null;
	}

	//保存用户和数据范围的对应关系
	private ActionForward addDataScope(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception{
		String str = request.getParameter("str");
		String opId = request.getParameter("opId");
		
		ReturnMessage message = operatorService.addDataScope(opId,str);
		
		response.setContentType("text/xml;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.print(message.toXMLString());
		out.flush();
		out.close();
		return null;
	}

	//向服务器请求勾选了哪些方法并返回给修改树状窗口
	private ActionForward methodIsCheck(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id = request.getParameter("id");
		String xmlString = operatorService.methodIsCheck(id);
		response.setContentType("text/xml;charset=UTF-8");
//		System.out.println(xmlString);
		PrintWriter out = response.getWriter();
		out.print(xmlString);
		out.flush();
		out.close();
		return null;
	}
	
	//保存方法和功能的关系
	private ActionForward addMethod(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) throws Exception{
		String str = request.getParameter("str");
		String id = request.getParameter("id");//角色ID
		String functionStr = request.getParameter("functionStr");//功能id
		ReturnMessage message = operatorService.addMethod(str,id,functionStr);
		
		response.setContentType("text/xml");
		PrintWriter out = response.getWriter();
		out.print(message.toXMLString());
		out.flush();
		out.close();
		return null;
	}
	
	
	private ActionForward query(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		return null;
	}
	
	private ActionForward updatePassword(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String id = request.getParameter("id");
		String password = request.getParameter("password");
		
		Operator operator = new Operator();
		operator.setOpID(id);
		operator.setOpPassword(password);
		
		ReturnMessage returnMessage = null;
		try
		{
			 operatorService.updateOperatorPassword(operator);
			 returnMessage = new ReturnMessage("1","更新成功");
		}
		catch (Exception e)
		{
			// TODO: handle exception
			 returnMessage = new ReturnMessage("0","更新成功"+ e.getMessage());
			 logger.error(e);
		}
		
		
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(returnMessage.toXMLString());
		out.flush();
		out.close();
		
		return null;
	}
	
	private ActionForward detail(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String operatorID = request.getParameter("operatorID");
		Operator operator = new Operator();
		operator.setOpID(operatorID);
		
		String reponseXML = operatorService.selectOperator(operator).toXML();
		
//		System.out.println(reponseXML);
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(reponseXML);
		out.flush();
		out.close();
		return null;
	}
	
	private ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String id = request.getParameter("id");
		Operator operator = new Operator();
		operator.setOpID(id);
		ReturnMessage returnMessage = null;
		try
		{
			 operatorService.deleteOperator(operator);
			 returnMessage = new ReturnMessage("1","删除成功");
		}
		catch (Exception e)
		{
			// TODO: handle exception
			 returnMessage = new ReturnMessage("0","删除失败"+ e.getMessage());
			 logger.error(e);
		}
		
		
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(returnMessage.toXMLString());
		out.flush();
		out.close();
		
		return null;
	}
	
	private ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
 		String id = request.getParameter("id");
		String workNO = request.getParameter("workNO");
		String name = request.getParameter("name");
		String job = request.getParameter("job");
		String smfID = request.getParameter("smfID");
		String status = request.getParameter("status");
		String maxDate = request.getParameter("maxDate");
		String tel = request.getParameter("tel");
		String qq = request.getParameter("qq");
		String email = request.getParameter("email");
		String memo = request.getParameter("memo");
		
		Operator operator = new Operator();
		operator.setOpID(id);
		operator.setOpWorkno(workNO);
		operator.setOpName(name);
		operator.setOpSmfID(smfID);
		operator.setOpJob(job);
		operator.setOpStatus(status);
		operator.setOpMaxDate(maxDate);
		operator.setOpQQ(qq);
		operator.setOpTel(tel);
		operator.setOpEmail(email);
		operator.setOpMemo(memo);
		
		ReturnMessage returnMessage = null;
		try
		{
			 operatorService.updateOperatorWithoutPassword(operator);
			 returnMessage = new ReturnMessage("1","更新成功");
		}
		catch (Exception e)
		{
			// TODO: handle exception
			 returnMessage = new ReturnMessage("0","更新失败"+ e.getMessage());
			 logger.error(e);
		}
		
		
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(returnMessage.toXMLString());
		out.flush();
		out.close();
		
		return null;
	}
	
	private ActionForward insert(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String workNO = request.getParameter("workNO");
		String name = request.getParameter("name");
		String job = request.getParameter("job");
		String smfID = request.getParameter("smfID");
		String status = request.getParameter("status");
		String maxDate = request.getParameter("maxDate");
		String tel = request.getParameter("tel");
		String qq = request.getParameter("qq");
		String email = request.getParameter("email");
		String memo = request.getParameter("memo");
		
		Operator operator = new Operator();
		operator.setOpWorkno(workNO);
		operator.setOpName(name);
		operator.setOpSmfID(smfID);
		operator.setOpJob(job);
		operator.setOpStatus(status);
		operator.setOpMaxDate(maxDate);
		operator.setOpQQ(qq);
		operator.setOpTel(tel);
		operator.setOpEmail(email);
		operator.setOpMemo(memo);
		
		ReturnMessage returnMessage = null;
		try
		{
			 String opID = operatorService.insertOperator(operator);
			 returnMessage = new ReturnMessage("1",opID);
		}
		catch (Exception e)
		{
			// TODO: handle exception
			 System.out.println("-------------------错误测试");
			 returnMessage = new ReturnMessage("0",e.getMessage());
			 logger.error(e);
		}
		
		System.out.println("-------------"+returnMessage);
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(returnMessage.toXMLString());
		out.flush();
		out.close();
		
		return null;
	}
	
	private ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String username = request.getParameter("username");
		String loginIP = request.getParameter("loginIP");
		String password = request.getParameter("password");
		
		ReturnMessage returnMessage  = null;
		
		try
		{
			returnMessage = operatorService.validOperator(username, loginIP, password);
			
			if(StringUtil.toInteger(returnMessage.getFlag())  == 1)
			{
				HttpSession session = request.getSession();
				Operator currentOperator = new Operator();
				currentOperator.setOpID(returnMessage.getBody());
				Operator operator = operatorService.selectOperator(currentOperator);
				session.setAttribute("operator", operator);
			}
		}
		catch (Exception e)
		{
			// TODO: handle exception
			returnMessage = new ReturnMessage("-1",e.getMessage());
			logger.error("loginError", e);
			e.printStackTrace();
		}
		
		
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(returnMessage.toXMLString());
		out.flush();
		out.close();
		
		return null;
	}
	
	private ActionForward logout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		HttpSession session = request.getSession();
		
		session.removeAttribute("operator");
		
		return mapping.findForward("index");
	}
	
	
	private ActionForward modifyPassword(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		
		String operatorID = request.getParameter("operatorID");
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword");
		String confirmPassword = request.getParameter("confirmPassword");
		
		ReturnMessage returnMessage  = null;
		
		try
		{
			returnMessage = operatorService.modifyPassword(operatorID, oldPassword, newPassword, confirmPassword);
			
		}
		catch (Exception e)
		{
			// TODO: handle exception
			returnMessage = new ReturnMessage("-1",e.getMessage());
			logger.error("loginError", e);
			e.printStackTrace();
		}
		
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(returnMessage.toXMLString());
		out.flush();
		out.close();
		
		return null;
	}
	
	private ActionForward loading(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception
	{
		functionService.methodFilter(request,response);
		
		List<OperatorStatus> operatorStatusList = operatorStatusService.selectAllOperatorStatus();
		
		request.setAttribute("operatorStatusList", operatorStatusList);
		return  mapping.findForward("loading");
	}
	
	
	private ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		
		String reponseXML = null;
		
		Operator operator = new Operator();
		operator.initParametes(request);
		
		String filter = operator.getFilterString();
		String page = operator.getPageString();
		if(filter.length() != 0 && page.length() != 0){
			operator.setPageString("");
		}
		int counts = operatorService.selectAllOperatorCount(operator);	
		List<Operator> operatorList = operatorService.selectAllOperator(operator);
		int pageCount =JQGridUtil.pageCount(counts ,operator.getRows());
		
		reponseXML = operatorService.getOperatorList(operatorList, operator.getPage(),pageCount, counts).toXML();
		
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(reponseXML);
		out.flush();
		out.close();
		return null;
	}
	
	
	
	private ActionForward selectStreetChargers(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		
		String reponseXML = null;
		String streetID = request.getParameter("streetID");
		List<Operator> operatorList = operatorService.selectStreetCharger(streetID);
		
		StringBuffer xmlString = new StringBuffer();
		xmlString.append("<?xml version='1.0' encoding='utf-8'?>");
		xmlString.append("<charges>");
		for(Operator charger:operatorList)
		{
			xmlString.append("<option value=\""+charger.optionValue()+"\" title=\""+charger.optionTitle()+"\">");
			xmlString.append(charger.optionText());
			xmlString.append("</option>");
		}
		xmlString.append("</charges>");
		
		reponseXML = xmlString.toString();
		
//		System.out.println(reponseXML);
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(reponseXML);
		out.flush();
		out.close();
		return null;
		
	}
	
}